package org.real.guetshop.controller.user;

import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
//import com.github.binarywang.wx.miniapp.bean.WxMaUser;
//import com.github.binarywang.wx.miniapp.bean.WxMaOAuth2AccessToken;
//import com.github.binarywang.wx.miniapp.service.WxMaService;
import me.chanjar.weixin.mp.api.WxMpService;
import org.real.guetshop.pojo.dto.EditPwDTO;
import org.real.guetshop.pojo.dto.UserLoginDTO;
import org.real.guetshop.pojo.dto.UserRegisterDTO;
import org.real.guetshop.pojo.dto.UserUpdateDTO;
import org.real.guetshop.pojo.entity.User;
import org.real.guetshop.pojo.vo.UserLoginVO;
import org.real.guetshop.propertis.JwtProperties;
import org.real.guetshop.result.Result;
import org.real.guetshop.service.UserService;
import org.real.guetshop.utils.JwtUtil;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@Slf4j
@RequestMapping("/user/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private JwtProperties jwtProperties;

//    @Resource
//    private WxMpService wxMpService;
//
//    @Resource
//    private WxMaService wxMaService;

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO uerLoginDTO){
        log.info("用户登录：{}",uerLoginDTO);
        User user = userService.login(uerLoginDTO);

        //获得当前时间的秒数
        long nowTime = System.currentTimeMillis();

        //登录成功下发令牌
        String token = JwtUtil.createToken(user.getId()
                , new Date(nowTime)
                , new Date(nowTime + jwtProperties.getUserTtl()));

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .userName(user.getUsername())
                .name(user.getName())
                .token(token)
                .tx(user.getTx())
                .email(user.getEmail())
                .build();

        return Result.success(userLoginVO);
    }

    /**
     * 用户注册
     * @param userRegisterDTO
     * @return
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO){
        log.info("用户注册：{}",userRegisterDTO);

        userService.insert(userRegisterDTO);
        return Result.success();
    }

    /**
     * 根据id获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/userInfo/{userId}")
    @Operation(summary = "根据id获取用户信息")
    public Result<User> getUserInfo(@PathVariable(value = "userId") Integer userId){
        log.info("获取用户信息，用户id：{}",userId);
        User user = userService.getUserById(userId);
        return Result.success(user);
    }

    /**
     * 用户信息更新
     * @param userUpdateDTO
     * @return
     */
    @PutMapping("/update")
    @Operation(summary = "用户信息更新")
    public Result update(@RequestBody UserUpdateDTO userUpdateDTO){
        log.info("用户信息更新：{}",userUpdateDTO);
        userService.update(userUpdateDTO);
        return Result.success();
    }

    /**
     * 用户修改密码
     * @param editPwDTO
     * @return
     */
    @PostMapping("/pwEdit")
    public Result pwEdit2(@RequestBody EditPwDTO editPwDTO){
        log.info("用户开始修改密码--校验验证码...");
        userService.editPw(editPwDTO);
        return Result.success();
    }

//    @RequestMapping("/wx/login")
//    public String wxLogin(){
//        String redirectUrl = "http://your_domain.com/wx/callback";
//        String url = wxMpService.getOAuth2Service().buildAuthorizationUrl(redirectUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
//        return "redirect:" + url;
//    }
//
//    @RequestMapping("/wx/callback")
//    public String wxCallback(@RequestParam("code") String code,
//                             @RequestParam("state") String state,
//                             HttpSession session) {
//        try {
//            // 使用 wxMaService 获取 OAuth2.0 授权的 access token
//            WxMaOAuth2AccessToken accessToken = wxMaService.oauth2getAccessToken(code);
//            // 使用 access token 获取用户信息
//            WxMaUser wxMaUser = wxMaService.oauth2getUserInfo(accessToken, null);
//            // 获取用户信息并处理
//            // 例如，可以将用户信息存储到 session 中
//            session.setAttribute("wxUser", wxMaUser);
//
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//            // 处理错误情况，例如记录日志、设置错误信息到 session 等
//        }
//        return "redirect:/";
//    }
}
